package com.a2.appa3.model;

import android.util.Log;
import android.widget.Toast;

import com.a2.appa3.R;
import com.a2.appa3.ui.activity.BaseActivity;
import com.a2.appa3.util.SYSOUtils;

import java.io.InterruptedIOException;
import java.net.SocketException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2017/5/12.
 * CustomObserver
 */
public abstract class CustomObserver<T> implements Observer<T> {
    /**
     * @param baseActivity     Activity引用
     * @param dialogCancelable DialogCancelable默认false
     */
    protected CustomObserver(BaseActivity baseActivity, boolean dialogCancelable) {
        this.baseActivity = baseActivity;
        this.dialogCancelable = dialogCancelable;
    }

    /**
     * @param baseActivity Activity引用
     */
    protected CustomObserver(BaseActivity baseActivity) {
        this.baseActivity = baseActivity;
    }

    /**
     * 不显示Dialog构造方法
     */
    protected CustomObserver() {

    }

    private BaseActivity baseActivity;
    private boolean dialogCancelable;

    @Override
    public void onSubscribe(Disposable d) {
        onSubscribeCustom(d);
        if (baseActivity != null) {
            baseActivity.getDisposableList().add(d);//添加disposableList
//            if (baseActivity.lottieDialog != null) {
//                baseActivity.lottieDialog.setCancelable(dialogCancelable);
//                baseActivity.lottieDialog.show();//自动显示Dialog
//            }
        }
    }

    @Override
    public void onError(Throwable e) {
        SYSOUtils.errLog(e.getMessage(), e);
        dismissDialog();
        onErrorCustom(e);
        if (e instanceof InterruptedIOException
                || e instanceof SocketException
                || e instanceof UnknownHostException)
            if (baseActivity != null)
                Toast.makeText(baseActivity, R.string.toast_interruptedIOException, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onComplete() {
        dismissDialog();
    }

    /**
     * 隐藏Dialog
     */
    private void dismissDialog() {
//        if (baseActivity != null
//                && baseActivity.lottieDialog != null
//                && baseActivity.lottieDialog.isShowing()) {
//            baseActivity.lottieDialog.dismiss();
//        }
    }
    @Override
    public void onNext(T t) {
        if (null != t) {
            try {
                onCustomNext(t);
            } catch (Exception e) {
                Log.e("xdh",e.toString());
            }
        }
    }
    /**
     * 经过初筛的返回体
     *
     * @param t
     */
    protected abstract void onCustomNext(T t);
    /**
     * onSubscribe具体处理
     *
     * @param disposable
     */
    protected abstract void onSubscribeCustom(Disposable disposable);

    /**
     * 异常具体处理
     *
     * @param e
     */
    protected abstract void onErrorCustom(Throwable e);
}
